package kontrol;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import userdata.User;
import database.DALException;
import database.MySQLOperatoerDAO;
import database.OperatoerDTO;

/**
 * Servlet implementation class Main
 */
@WebServlet({ "/", "/Logout" })
public class Main extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Main() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getRequestURI().endsWith("/Logout")) {
			request.getSession().invalidate();
			response.sendRedirect(request.getContextPath());
			
		} else {
			OperatoerDTO dto = null;
			MySQLOperatoerDAO dao;

			try {
				dao = new MySQLOperatoerDAO();
				dto = dao.getOperatoer(request.getUserPrincipal().getName());
			} catch (DALException e) {
				e.printStackTrace();
			}

			User currentUser = new User();
			currentUser.setAllData(dto);

			request.setAttribute("data", currentUser);

			request.getRequestDispatcher("/WEB-INF/home.jsp").forward(request,
					response);

		}
	}
}
